/*
 * Copyright (C) 2009 Rob Cash
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * LocalFileSubscriptionDAO.java
 * 
 * Created on Jan 5, 2009 at 9:39:19 PM
 */

package org.robcash.apps.messagepopup.dataaccess.dao.impl;

import static org.robcash.apps.messagepopup.Constants.MESSAGE_POPUP_NS;
import static org.robcash.apps.messagepopup.Constants.MESSAGE_POPUP_SCHEMA_RESOURCE;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.MarshalException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationException;
import javax.xml.namespace.QName;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.robcash.apps.messagepopup.MessageException;
import org.robcash.apps.messagepopup.dataaccess.dao.SubscriptionDAO;
import org.robcash.apps.messagepopup.vo.impl.LocalFileSubscriptionStoreLocator;
import org.robcash.xmlns.apps._2009._01.MessagePopup.SubscriptionStoreType;
import org.xml.sax.SAXException;

/**
 *
 * @author Rob
 */
public class LocalFileSubscriptionDAO implements SubscriptionDAO {

    /**
     * Load a subscription store
     * @return Subscription store
     * @throws MessageException Thrown if the subscription store cannot be
     * loaded
     */
    public SubscriptionStoreType loadSubscriptionStore()
            throws MessageException {

        File file = LocalFileSubscriptionStoreLocator.getLocation();
        if ( !file.exists() ) {
            return null;
        }
        SubscriptionStoreType store = null;

        try {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(getClass().getResource(
                    MESSAGE_POPUP_SCHEMA_RESOURCE));
            JAXBContext jc = JAXBContext.newInstance(SubscriptionStoreType.class.getPackage().getName());
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            unmarshaller.setSchema(schema);
            JAXBElement<SubscriptionStoreType> rootElement = (JAXBElement<SubscriptionStoreType>) unmarshaller.unmarshal(file);
            store = rootElement.getValue();
        }
        catch(SAXException se) {
            Logger.getLogger(LocalFileSubscriptionDAO.class.getName()).
                    log(Level.WARNING, "Subscription store schema is not valid", se);
            throw new MessageException(se);
        }
        catch(JAXBException e) {
            Logger.getLogger(LocalFileSubscriptionDAO.class.getName()).
                    log(Level.WARNING, "Error occurred while unmarshalling " +
                    "XML", e);
            throw new MessageException(e);
        }

        return store;
    }

    /**
     * Save a subscription store
     * @param store Subscription store to save
     * @throws MessageException Thrown if the subscription store cannot be
     * saved
     */
    public void saveSubscriptionStore(SubscriptionStoreType store)
            throws MessageException {
        File file = LocalFileSubscriptionStoreLocator.getLocation();
        try {
            if ( !file.getParentFile().exists() ) {
                file.getParentFile().mkdirs();
            }
            FileWriter out = new FileWriter(file);

            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(getClass().getResource(
                    MESSAGE_POPUP_SCHEMA_RESOURCE));
            JAXBContext jc = JAXBContext.newInstance(SubscriptionStoreType.class.getPackage().getName());
            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            m.setSchema(schema);
            m.marshal(new JAXBElement(new QName(
                    MESSAGE_POPUP_NS,
                    "SubscriptionStore"), SubscriptionStoreType.class, store),
                    out);
            out.close();
        }
        catch(IOException ioe) {
            Logger.getLogger(LocalFileSubscriptionDAO.class.getName()).
                    log(Level.WARNING, "Error occurred while writing to " +
                    "subscription store", ioe);
            throw new MessageException(ioe);
        }
        catch(SAXException se) {
            Logger.getLogger(LocalFileSubscriptionDAO.class.getName()).
                    log(Level.WARNING, "Subscription store schema is not valid", se);
            throw new MessageException(se);
        }
        catch (MarshalException ex) {
            Logger.getLogger(LocalFileSubscriptionDAO.class.getName()).
                    log(Level.WARNING, "Failed to save subscription store: " +
                    "SubscriptionStore could not be marshalled into XML", ex);
            throw new MessageException(ex);
        }
        catch (ValidationException ex) {
            Logger.getLogger(LocalFileSubscriptionDAO.class.getName()).
                    log(Level.WARNING, "Failed to save subscription store: " +
                    "SubscriptionStore does not pass XML validation", ex);
            throw new MessageException(ex);
        }
        catch(JAXBException e) {
            Logger.getLogger(LocalFileSubscriptionDAO.class.getName()).
                    log(Level.WARNING, "Error occurred while marshalling " +
                    "XML", e);
            throw new MessageException(e);
        }
    }

}
